<template>
  <div class="process-data-form">
    <!-- 操作栏 -->
    <div class="operation-bar mb-4">
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><plus /></el-icon> 新建
      </el-button>
      <el-input 
        v-model="searchQuery" 
        placeholder="输入查询内容" 
        class="search-input"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="success" @click="handleSearch">
            <el-icon><search /></el-icon> 查询
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 表格展示 -->
    <el-table 
      :data="filteredData" 
      border 
      stripe 
      style="width: 100%"
      :empty-text="loading ? '加载中...' : '暂无数据'"
    >
      <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="equipment" label="工序设备" align="center"></el-table-column>
      <el-table-column prop="dataName" label="数据名称" align="center"></el-table-column>
      <el-table-column prop="dataValue" label="数据" align="center"></el-table-column>
      <!-- 填报日期列添加排序功能 -->
      <el-table-column 
        prop="date" 
        label="填报日期" 
        align="center"
        sortable
        :sort-method="sortByDate"
      ></el-table-column>
      <el-table-column prop="savedTime" label="保存时间" align="center"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button 
            type="warning" 
            size="small" 
            @click="openEditDialog(scope.row)"
            icon="Edit"
          ></el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row.id)"
            icon="Delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="1000px"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <!-- 表头行 -->
        <div class="form-header form-row mb-2 font-bold">
          <div class="form-label equipment">工序设备</div>
          <div class="form-label data-name">数据名称</div>
          <div class="form-label data-value">数据</div>
          <div class="form-label date">填报日期</div>
          <div class="form-label remark">备注</div>
          <div class="form-label delete-btn"></div>
        </div>
        
        <el-descriptions column="1" border>
          <template v-for="(row, index) in formData" :key="index">
            <el-descriptions-item>
              <div class="form-row">
                <!-- 工序设备 -->
                <div class="form-group equipment">
                  <el-select 
                    v-model="row.equipment" 
                    placeholder="请选择"
                    class="form-item"
                    required
                    @change="handleEquipmentChange(index)"
                  >
                    <el-option 
                      v-for="item in equipmentOptions" 
                      :key="item" 
                      :label="item" 
                      :value="item"
                    ></el-option>
                  </el-select>
                </div>

                <!-- 数据名称 -->
                <div class="form-group data-name">
                  <el-select 
                    v-model="row.dataName" 
                    placeholder="请选择"
                    class="form-item"
                    required
                    :disabled="!row.equipment"
                  >
                    <el-option 
                      v-for="item in getRowDataNames(index)" 
                      :key="item" 
                      :label="item" 
                      :value="item"
                    ></el-option>
                  </el-select>
                </div>

                <!-- 数据值 -->
                <div class="form-group data-value">
                  <el-input 
                    v-model="row.dataValue" 
                    placeholder="请输入"
                    class="form-item"
                    required
                  ></el-input>
                </div>

                <!-- 日期 -->
                <div class="form-group date">
                  <el-date-picker
                    v-model="row.date"
                    type="date"
                    placeholder="选择日期"
                    class="form-item"
                    value-format="YYYY-MM-DD"
                    required
                  ></el-date-picker>
                </div>

                <!-- 备注 -->
                <div class="form-group remark">
                  <el-input 
                    v-model="row.remark" 
                    placeholder="请输入"
                    class="form-item"
                  ></el-input>
                </div>

                <!-- 删除行按钮 -->
                <div class="form-group delete-btn">
                  <el-button 
                    type="danger" 
                    icon="Delete" 
                    size="small" 
                    class="delete-row-btn"
                    @click="removeRow(index)"
                    :disabled="formData.length <= 1"
                  ></el-button>
                </div>
              </div>
            </el-descriptions-item>
          </template>
        </el-descriptions>

        <!-- 添加行按钮 - 仅在非编辑模式显示 -->
        <el-button 
          type="primary" 
          icon="Plus" 
          class="add-row-btn"
          @click="addRow"
          v-if="!currentEditId"
        >
          添加一行
        </el-button>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveData">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'ProcessDataForm',
  components: {
    Plus,
    Search,
    Edit,
    Delete
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 查询条件
      searchQuery: '',
      // 加载状态
      loading: false,
      
      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新建数据',
      formData: [],
      currentEditId: null,
      
      // 设备与数据名称的映射关系
      equipmentDataMap: {
        '车床A': ['温度', '转速', '精度', '加工时长'],
        '铣床B': ['温度', '压力', '进给速度', '切削量'],
        '磨床C': ['温度', '砂轮转速', '磨削深度', '光洁度'],
        '钻床D': ['主轴转速', '钻孔深度', '进给量', '冷却压力'],
        '冲压机E': ['压力', '行程次数', '模具温度', '冲压速度']
      }
    };
  },
  computed: {
    // 工序设备选项（从映射关系中获取所有键）
    equipmentOptions() {
      return Object.keys(this.equipmentDataMap);
    },
    
    // 过滤后的数据
    filteredData() {
      if (!this.searchQuery) return this.tableData;
      
      const query = this.searchQuery.toLowerCase();
      return this.tableData.filter(item => 
        item.equipment.toLowerCase().includes(query) ||
        item.dataName.toLowerCase().includes(query) ||
        item.dataValue.toLowerCase().includes(query) ||
        item.date.toLowerCase().includes(query) ||
        item.savedTime.toLowerCase().includes(query) ||
        item.remark.toLowerCase().includes(query)
      );
    }
  },
  methods: {
    get_dev_info_db(){
      this.tableData = [];
      try {
        // 实际项目中替换为真实的API地址                 
        this.http.get('api/wsz_shebei/base_data_search',
            {})
            .then((reslut_all) => {
              console.log(reslut_all)
              this.equipmentDataMap = {}
              var equipmentOptions = []
              var reslut = reslut_all["find_data_type"]
              for(let i=0;i<reslut.length;i++){
                if(equipmentOptions.includes(reslut[i]["device_name"])){
                  continue
                }else{
                  equipmentOptions.push(reslut[i]["device_name"])
                }
              }
              for(let j=0;j<equipmentOptions.length;j++){
                var per_opt_info = []
                for(let i=0;i<reslut.length;i++){
                  if(reslut[i]["device_name"] == equipmentOptions[j]){
                    if(reslut[i]["deta_type1"] != null){
                      per_opt_info.push(reslut[i]["deta_type1"])
                    }
                    if(reslut[i]["data_type2"] != null){
                      per_opt_info.push(reslut[i]["data_type2"])
                    }
                  }
                }
                this.equipmentDataMap[equipmentOptions[j]] = per_opt_info
              }
              var data_info_detail = reslut_all["find_data_detail"]
              for(let x=0;x<data_info_detail.length;x++){
                var per_info_ = {
                  id:data_info_detail[x]["Id"],
                  equipment:data_info_detail[x]["device_name"],
                  dataName:data_info_detail[x]["data_name"],
                  dataValue:data_info_detail[x]["data_detail"],
                  date:data_info_detail[x]["intime"],
                  savedTime: data_info_detail[x]["savetime"],
                }
                this.tableData.push(per_info_)
              }
              console.log("this.tableData",this.tableData)
            })
            .catch((error) => {
            console.log("失败", error);
            loadingInstance.close();                            
            });        
      } catch (error) {
        console.error('更新工单失败：', error);
        // ElMessage.error('更新工单失败，请稍后重试');
      }
    },
    // 获取指定行的数据名称选项
    getRowDataNames(index) {
      const equipment = this.formData[index]?.equipment;
      return equipment ? this.equipmentDataMap[equipment] : [];
    },
    
    // 处理设备选择变化
    handleEquipmentChange(index) {
      // 当设备改变时，重置数据名称
      this.formData[index].dataName = '';
    },

    // 获取中国时区当前日期 (YYYY-MM-DD)
    getCurrentDate() {
      const date = new Date();
      // 计算中国时区偏移 (UTC+8)
      const offset = 8 * 60 * 60 * 1000; // 8小时的毫秒数
      const chinaTime = new Date(date.getTime() + offset);
      return chinaTime.toISOString().split('T')[0];
    },
    
    // 获取中国时区当前时间 (YYYY-MM-DD HH:MM:SS)
    getCurrentDateTime() {
      const date = new Date();
      // 计算中国时区偏移 (UTC+8)
      const offset = 8 * 60 * 60 * 1000; // 8小时的毫秒数
      const chinaTime = new Date(date.getTime() + offset);
      
      // 格式化日期部分
      const year = chinaTime.getUTCFullYear();
      const month = String(chinaTime.getUTCMonth() + 1).padStart(2, '0');
      const day = String(chinaTime.getUTCDate()).padStart(2, '0');
      
      // 格式化时间部分
      const hours = String(chinaTime.getUTCHours()).padStart(2, '0');
      const minutes = String(chinaTime.getUTCMinutes()).padStart(2, '0');
      const seconds = String(chinaTime.getUTCSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 日期排序方法
    sortByDate(a, b) {
      return new Date(a.date) - new Date(b.date);
    },
    
    // 打开新建对话框
    openCreateDialog() {
      this.dialogTitle = '新建数据';
      this.currentEditId = null;
      this.formData = [{
        equipment: '',
        dataName: '',
        dataValue: '',
        date: this.getCurrentDate(), // 自动赋值中国时区当前日期
        remark: ''
      }];
      this.dialogVisible = true;
    },
    
    // 打开编辑对话框 - 添加id到formData
    openEditDialog(row) {
      this.dialogTitle = '编辑数据';
      this.currentEditId = row.id;
      this.formData = [{
        id: row.id,  // 将id带入formData
        equipment: row.equipment,
        dataName: row.dataName,
        dataValue: row.dataValue,
        date: row.date,
        remark: row.remark
      }];
      this.dialogVisible = true;
    },
    
    // 添加一行
    addRow() {
      this.formData.push({
        equipment: '',
        dataName: '',
        dataValue: '',
        date: this.getCurrentDate(),
        remark: ''
      });
    },
    
    // 移除一行
    removeRow(index) {
      this.formData.splice(index, 1);
    },
    delete_data(id){
      this.http.get('api/wsz_shebei/delete_data_id',
        {id:id})
        .then((reslut) => {
          console.log(reslut)
        })
        .catch((error) => {
        console.log("失败", error);
        loadingInstance.close();                            
        });
    },
    insert_update_db(opt_type,data,currentTime){
      console.log("2222222222222222222",opt_type)
      let mes_data_final = []
      mes_data_final.push(opt_type)
      var per_info = []
      for(let i=0;i<data.length;i++){
        var per_ = []
        var per_data = data[i]
        per_.push(per_data["equipment"])
        per_.push(per_data["dataName"])
        per_.push(per_data["dataValue"])
        per_.push(per_data["date"])
        per_.push(currentTime)
        per_.push(per_data["id"])  // 现在可以正确获取id了
        per_info.push(per_)
      }
      mes_data_final.push(per_info)
      let jsonString_mes_data = JSON.stringify(mes_data_final)
      this.http.get('api/wsz_shebei/base_data_input',
        {mes_data:jsonString_mes_data})
        .then((reslut) => {
          console.log(reslut)

        })
        .catch((error) => {
        console.log("失败", error);
        loadingInstance.close();                            
        });
    },
    
    // 保存数据
    saveData() {
      // 验证所有行的必填字段
      const isValid = this.formData.every(row => 
        row.equipment && row.dataName && row.dataValue && row.date
      );
      
      if (!isValid) {
        ElMessage.error('请填写所有必填字段（工序设备、数据名称、数据、日期为必填项）');
        return; // 验证失败不关闭对话框
      }
      
      // 显示加载状态
      this.loading = true;
      
      // 获取中国时区当前保存时间
      const currentTime = this.getCurrentDateTime();
      var edit_state = "新建"
      console.log("GGGGGGG",this.formData)
      // 模拟异步保存操作
      setTimeout(() => {
        if (this.currentEditId) {
          // 编辑模式 - 保持原保存时间不变
          const index = this.tableData.findIndex(item => item.id === this.currentEditId);
          if (index !== -1) {
            this.tableData[index] = {
              ...this.tableData[index],
              ...this.formData[0]
              // 不更新保存时间，保持首次保存时间
            };
            edit_state = "编辑"
            console.log("ssss",this.formData)
            this.insert_update_db(edit_state,this.formData,currentTime)
            ElMessage.success('数据更新成功');
          }
        } else {
          // 新建模式 - 添加新的保存时间到表格底部
          this.formData.forEach(row => {
            this.tableData.push({
              id: Date.now() + Math.floor(Math.random() * 1000),
              ...row,
              savedTime: currentTime // 添加中国时区保存时间
            });
          });
          this.insert_update_db(edit_state,this.formData,currentTime)
          this.get_dev_info_db();
          ElMessage.success(`成功添加 ${this.formData.length} 条数据`);
        }
        
        // 保存成功后关闭对话框
        this.dialogVisible = false;
        this.loading = false;
      }, 500); // 模拟网络延迟
    },
    
    // 删除数据
    handleDelete(id) {
      console.log("GSSDASDFSDFAEFG",id)
      ElMessageBox.confirm(
        '确定要删除这条数据吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.delete_data(id)
        this.tableData = this.tableData.filter(item => item.id !== id);
        console.log("?????????????",this.tableData)
        ElMessage.success('数据已删除');
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 处理查询
    handleSearch() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    
    // 初始化数据
    initData() {
      // 为初始数据添加中国时区保存时间
      const initTime = this.getCurrentDateTime();
      // this.tableData = [];
       this.tableData = [];
    }
  },
  mounted() {
    this.get_dev_info_db();
    // 组件挂载时初始化数据
    this.initData();
  }
};
</script>

<style scoped>
/* 样式部分保持不变 */
.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10px;
  padding-top: 10px;
  padding-right: 10px;
}

.search-input {
  width: 300px;
}

/* 表单样式调整 */
.form-header {
  color: #606266;
  font-weight: 500;
  padding: 5px 0;
  /* padding-left: 10px; */
}

.form-row {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 5px 0;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 5px;
  padding-left: 10px;
}

.form-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.form-item {
  width: 100%;
}

/* 各列宽度分配 */
.equipment {
  flex: 1.3;
}

.data-name {
  flex: 1.3;
}

.data-value {
  flex: 1;
}

.date {
  flex: 1;
}

.remark {
  flex: 1.5;
}

.delete-btn {
  width: 40px;
  display: flex;
  justify-content: center;
}

.delete-row-btn {
  width: 40px;
  padding: 0;
}

.add-row-btn {
  margin-top: 10px;
}
</style>